#include "login_cmd_module.h"

#include <boost/algorithm/string.hpp>
#include <boost/asio.hpp>
using namespace boost;
using namespace boost::asio;

#include <common/base/server_mgr.h>
#include <common/log/log.h>
#include <common/net/message_parse.h>
#include <common/net/session.h>
#include <common/net/session_mgr.h>

#include <protocols/protos/common.pb.h>
using namespace proto::common;
#include <protocols/protos/login.pb.h>
using namespace proto::login;

#include "base/sub_server_mgr.h"

bool LoginCmdModule::doDispatch(const std::shared_ptr<Session>& session,
                               const std::string& cmd,
                               const std::string& params)
{
    if (cmd == "login")
    {
        return onLogin(session, cmd, params);
    }
    if (cmd == "test")
    {
        return onTest(session, cmd, params);
    }
    return false;
}

std::shared_ptr<Session> g_lgSession;

std::shared_ptr<Session> getLgSession()
{
    if (g_lgSession)
        return g_lgSession;

    auto sessionMgr = ServerMgr::get().getMgr<SessionMgr>(ManagerType::eSession);
    if (!sessionMgr)
    {
        LOG_ERROR("Session manager not inited.");
        return false;
    }



    std::vector<std::shared_ptr<Session>> sessions;
    sessionMgr->getConnSessions(ServerType::eLoginGate, SessionType::eNormal, sessions);
    if (sessions.empty())
    {
        LOG_DEBUG("Session not found.");
        return std::shared_ptr<Session>();
    }



    g_lgSession = sessions[0];
    return g_lgSession;
}

bool LoginCmdModule::onLogin(const std::shared_ptr<Session>& session,
                             const std::string& cmd,
                             const std::string& params)
{
    std::string accID = "test001";
    std::string source = "testSource";

    std::vector<std::string> vparam;
    boost::split(vparam, params, boost::is_any_of(" "));

    if (vparam.size() >= 2)
    {
        accID = vparam[0];
        source = vparam[1];
    }

    LoginReq req;
    req.set_acc_name(accID);
    req.set_source(source);

    return getLgSession()->sendMsg(proto::common::ModuleType::eLogin, C2S_LOGIN_REQ, req);
}

bool LoginCmdModule::onTest(const std::shared_ptr<Session>& session,
                             const std::string& cmd,
                             const std::string& params)
{
    TestReq req;
    return getLgSession()->sendMsg(proto::common::ModuleType::eLogin, C2S_TEST_REQ, req);
}
